﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;

namespace CustomerService
{
    public partial class OrderTab : System.Web.UI.UserControl
    {
        private SalesManagerEntities _context;
        private tblCustomer _customer;
        private IOrderedEnumerable<tblOrderHeader> _orderList;

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public new void Load(SalesManagerEntities context, tblCustomer customer)
        {
            _context = context;
            _customer = customer;
            TabContainer1.Enabled = _context.tblOrderHeader.Local.Where(p=>p.CustomerID == customer.CustomerID).Count() > 0;
            
            _orderList = _context.tblOrderHeader.Local.Where(p=>p.CustomerID == customer.CustomerID).OrderByDescending(oh=>oh.OrderDate);
            lvOrderList.DataSource = _orderList;
            if (_orderList.Count() > 0 && lvOrderList.SelectedIndex < 0)
                lvOrderList.SelectedIndex = 0;
            lvOrderList.DataBind();

//            if (_orderList.Count() > 0 && lvOrderList.SelectedIndex < 0)
//                lvOrderList.SelectedIndex = 0;

            SetDetail(false);
        }

        protected void OrderListSelectedChanged(object sender, EventArgs e)
        {
        }

        protected void OrderListSelectedIndexChanging(object sender, ListViewSelectEventArgs e)
        {
            lvOrderList.SelectedIndex = e.NewSelectedIndex;
            lvOrderList.DataSource = _orderList;
            lvOrderList.DataBind();
            SetDetail(true);
        }

        private void SetDetail( bool forceUpdate )
        {
            if (lvOrderList.SelectedIndex >= 0)
            {
                tblOrderHeader oh = _orderList.ElementAt(lvOrderList.SelectedIndex);

                ((OrderDetailTab)TabContainer1.FindControl("TabPanelDetails").FindControl("tabOrderDetail"))
                    .Load(_context, _orderList.ElementAt(lvOrderList.SelectedIndex), forceUpdate, UpdatePanel4);
                ((tabPayment)TabContainer1.FindControl("tabPayment").FindControl("tabPayment1"))
                    .Load(_context, _orderList.ElementAt(lvOrderList.SelectedIndex), forceUpdate);
                ((tabShipTo)TabContainer1.FindControl("TabPanelShipping").FindControl("tabShipTo"))
                    .Load(_context, _orderList.ElementAt(lvOrderList.SelectedIndex), forceUpdate);
                ((tabRefundsReturns)TabContainer1.FindControl("tabPanelRefunds").FindControl("tabRefundsReturns"))
                    .Load(_context, _orderList.ElementAt(lvOrderList.SelectedIndex), forceUpdate);
                IEnumerable<tblTransaction> transactions = from c in _context.tblTransaction.Local
                                   where c.OrderHeader == _orderList.ElementAt(lvOrderList.SelectedIndex)
                                   orderby c.CreateDate descending
                                   select c;
                ((TransactionsTab)TabContainer1.FindControl("tabPanelTransactions").FindControl("tabTransactions"))
                    .Load(_context, transactions);
                ((tabTracking)TabContainer1.FindControl("TabPanelTracking").FindControl("tabTracking"))
                    .Load(_context, _orderList.ElementAt(lvOrderList.SelectedIndex), forceUpdate);
                ((OrderSourceIDTab)TabContainer1.FindControl("TabPanelOrderSourceIDs").FindControl("tabOrderSourceIDs"))
                    .Load(_context, _context.tblAltOrderID.Local.Where(p => p.OrderID == oh.OrderID));
            }
        }

        protected void btnAddNewOrder_Click(object sender, EventArgs e)
        {
            OwnerEntities oe = new OwnerEntities();
            tblOwner own = oe.tblOwner.Find(new object[] { _customer.OwnerID });

            tblOrderHeader newOrder = new tblOrderHeader();
            newOrder.Customer = _customer;
            newOrder.ShipTo_Person = _customer.Person;
            newOrder.ShipTo_Address = _customer.Person.Address;
            newOrder.OwnerID = _customer.OwnerID;
            newOrder.AgentID = _context.UserID();
            newOrder.ProcessorCode = own.ProcessorCode;
            
            // in "Pending" status
            newOrder.OrderStatus = _context.codeOrderStatus.Find(new object[] { "P" });
            string orderOriginCode = ConfigurationManager.AppSettings["OrderOrigin"];
            newOrder.OrderOriginCode = orderOriginCode;

            _context.tblOrderHeader.Add(newOrder);
            //_context.SaveAllChanges(_customer.CustomerID);

            // Get orders for this customer sorted by the most recent shipment dates or projeced shipment date.
            _orderList = _context.tblOrderHeader.Local.Where(p=>p.CustomerID == _customer.CustomerID).OrderByDescending(oh => oh.RecentShippedDate);
            lvOrderList.DataSource = _orderList;
            lvOrderList.SelectedIndex = 0;
            lvOrderList.DataBind();

            SetDetail(true);
        }

        protected string ShowButton(string name)
        {
            if (_orderList != null && lvOrderList.SelectedIndex >= 0 && lvOrderList.SelectedIndex < _orderList.Count())
            {
                tblOrderHeader oh = _orderList.ElementAt(lvOrderList.SelectedIndex);
                if (name == "Hold")
                    return (oh.OrderStatusCode == "P") ? "display:block;" : "display:none;";
                if (name == "Release")
                    return (oh.OrderStatusCode == "H") ? "display:block;" : "display:none;";
            }
            return "display:none;";
        }

        protected void PopupCommand_Command(Object sender, CommandEventArgs e)
        {
            tblOrderHeader oh = _orderList.ElementAt(lvOrderList.SelectedIndex);
            if (e.CommandName == "Copy")
            {
                tblOrderHeader newOrder = new tblOrderHeader();
                newOrder.Customer = _customer;
                newOrder.ShipTo_Person = _customer.Person;
                newOrder.ShipTo_Address = _customer.Person.Address;
                newOrder.OwnerID = _customer.OwnerID;
                newOrder.AgentID = _context.UserID();

                // in "Pending" status
                newOrder.OrderStatus = _context.codeOrderStatus.Find(new object[] { "P" });
                string orderOriginCode = ConfigurationManager.AppSettings["OrderOrigin"];
                newOrder.OrderOriginCode = orderOriginCode;

                newOrder.Shipping = oh.Shipping;
                newOrder.Taxes = oh.Taxes;
                newOrder.tblAccount = oh.tblAccount;
                newOrder.PromotionID = oh.PromotionID;
                newOrder.PreferredCarrier = oh.PreferredCarrier;

                _context.tblOrderHeader.Add(newOrder);

                foreach (tblOrderDetail od in oh.OrderDetails.Where(c=>c.Product.SalableItem || 
                    (c.Product.ReorderProduct != null && c.Product.ReorderProduct.SalableItem)))
                {
                    tblOrderDetail newOrderDetail = new tblOrderDetail();
                    newOrderDetail.OrderHeader = newOrder;
                    newOrderDetail.ImportDate = DateTime.Now;
                    newOrderDetail.PreferredCarrier = od.PreferredCarrier;
                    newOrderDetail.Product = od.Product.ReorderProduct ?? od.Product;
                    newOrderDetail.Qty = od.Qty;
                    newOrderDetail.UnitPrice = od.UnitPrice;
                    newOrderDetail.UnitShipping = od.UnitShipping;
                    _context.tblOrderDetail.Add(newOrderDetail);
                }

                //_context.SaveAllChanges(_customer.CustomerID);

                _orderList = _context.tblOrderHeader.Local.Where(p => p.CustomerID == _customer.CustomerID).OrderByDescending(o => o.OrderDate);
                lvOrderList.DataSource = _orderList;
                lvOrderList.SelectedIndex = _orderList.ToList().FindIndex(c=>c == newOrder);
                lvOrderList.DataBind();

                SetDetail(true);
            }

            if (e.CommandName == "Release")
            {
                oh.OrderStatus = _context.codeOrderStatus.Find(new object[] { "P" });
                lvOrderList.DataBind();
            }

            if (e.CommandName == "Hold")
            {
                oh.OrderStatus = _context.codeOrderStatus.Find(new object[] { "H" });
                lvOrderList.DataBind();
            }
        }


        protected void OrderListSelectedIndexChanged(object sender, EventArgs e)
        {
        }
    }
}